import React, { useEffect, useState } from 'react'
import "@/assets/css/activityMsg.scss"
import HeadBack from "@/components/HeadBack"

import newImg from "@/assets/images/newImg.png"
import endImg from "@/assets/images/endImg.png"
import {getPageMsgs} from "@/utils/dataUtil"
import { InfiniteScroll, PullToRefresh } from 'antd-mobile'
import { timeConversion, compareToDate, timeDiff, getCurrentDate } from "@/utils/dateUtil"
import { useNavigate } from 'react-router-dom'


export default function ActivityMsg() {

  const navigate = useNavigate();

  const [data, setData] = useState([])
  const [hasMore, setHasMore] = useState(true);
  const [page, setPage] = useState(1);


  async function loadMore() {
    setPage(p => p+1);
    const res = await getPageMsgs(page);
    if(res.status === 1) {
      setData(val => [...val, ...res.data]);
      setHasMore(res.data.length > 0)
    } else {
      setHasMore(false);
    }
  }

  async function loadRefresh() {
    setPage(1);
    const res = await getPageMsgs(1);
    if(res.status === 1) {
      setHasMore(true)
      setData(res.data);
    }
  }


  useEffect(() => {
    getPageMsgs(1).then(res => {
      if(res.status === 1) {
        setHasMore(true)
        setData(res.data);
      }
    })
  }, [])

  //点击跳转到活动页面
  const clickActivityItem = (id) => {
    navigate("/detail", {state: {id: id}})
  }

  useEffect(() => {
    window.scrollTo(0, 0)
  }, [])
  return (
    <>
    <HeadBack background={"#F5F5F5"} backTit={""}  isHome="back"></HeadBack>
    <div className='acContainer'>

      <PullToRefresh onRefresh={loadRefresh}>
        {/* 标题 */}
        <div className='acTit'>消息通知</div>

        {/* 每条消息的item */}
        <div className='acMsgUl' style={{minHeight: "100vh"}}>
          {data.map((item, index) => (
            <div className='acMsgLi' key={index} onClick={() => clickActivityItem(item.id)}>
                <div className='acMsgLiLeft'>
                    <div className='acMsgImgBox'>
                        <img className='acMsgImg' src={item.expire === 1 ? newImg : endImg} alt='' />
                    </div>
                    <div className='acMsgTxtBox'>
                        <div className='acMsgTxtTit'>{
                          item.expire === 1 ? "活动上新" : "活动即将结束"
                        }</div>
                        <div className='acMsgTxtIntro'>
                          {item.activityName}{item.expire === 1 ? "活动上新了" : (timeDiff(getCurrentDate(), item.endDate) <= 0 ? "活动今天就结束了" : `活动还有${timeDiff(getCurrentDate(), item.endDate)}天就结束了`)}
                        </div>
                    </div>
                </div>
                <div className='acMsgLiDate'>{timeConversion(item.createTime)}</div>
            </div>))
          }
        </div>

      </PullToRefresh>
      

      {
        data.length >= 20 && <InfiniteScroll loadMore={loadMore} hasMore={hasMore} />
      }
      
    </div>

    </>
  )
}
